//
//  RaeRequestApiExtension.swift
//  77Club
//
//  Created by Apple on 2024/8/26.
//

import Foundation
import Alamofire
import AdSupport

extension RaeRequestApi {
    
    /// 请求全路径
    /// Request Full Path
    private var urlPath: String {
        let BaseUrl = RaeRequestParameterConfig.shared.baseUrlString
        let urlString = BaseUrl + path
        return urlString
    }
    
    /// 请求全路径(没有V3的地址)
    /// Request Full Path
    private var urlHalfPath: String {
        let BaseUrl = RaeRequestParameterConfig.shared.baseUrlStr
        let urlString = BaseUrl + path
        return urlString
    }
    
    /// 请求V5全路径
    /// Request Full Path
    private var V5UrlPath: String {
        let BaseUrl = RaeRequestParameterConfig.shared.baseUrlV5String
        let urlString = BaseUrl + path
        return urlString
    }
    
    /// 不需要token的接口，需要单独添加case
    /// For the interface that does not require a token, you need to add a case separately
    var isNeedToken: Bool {
//        switch self {
//        case .login: return false
//        case .register: return false
//        case .emailLogin: return false
//        default: return true
//        }
        return true
    }
    
    /// 是否是GET请求
    /// is GET Request
    var isGetRequest: Bool {
        switch self {
        case .report: return false
            
        default:
            return true
        }
    }
    
    /// 是否是上传图片接口
    /// is UPLOAD Image
    private var isUploadImage: Bool {
        switch self {
        case .upload:
            return true
        default:
            return false
        }
    }
    
    /// 是否是完全路径
    var isFullUrlRequest: Bool {
        switch self {
        case .searchGames: return false
        case .openService: return false
        case .updateUserInfo: return false
        case .commitGame: return false
        case .realVerfity: return false
        case .addAddress: return false
        case .delAddress: return false
        case .resetPassword: return false
        case .editPassword: return false
            
        default:
            return true
        }
    }
    
    /// 是否是V5路径
    var isV5UrlRequest: Bool {
        switch self {
        case .pushCommunityPost: return true
        case .addStrategyCommit: return true
        case .report: return true
        case .infolist: return true
        case .dynamicGame: return true
        case .shequReport: return true
        case .dynamicTopic: return true
        case .editSquareInfo: return true
        case .forumFollowSetting: return true
        case .editAdminPerm: return true
        case .searchPost: return true
        case .communityPostList: return true
        case .squareMemberList: return true
        case .searchDynamic: return true
        case .collectForum: return true
            
        default:
            return false
        }
    }
    
    /// 是否需要在header添加uid
    /// is GET Request
    var isUidRequest: Bool {
        switch self {
        case .delAddress: return false
            
        default:
            return true
        }
    }
    
    /// GET请求地址
    /// Get Request URL
    private var getRequestUrl: String {
        switch self {
        case .login(let user_name, let passwd, let t, let sign): return urlHalfPath + "&passwd=\(passwd)&user_name=\(user_name)&t=\(t)&sign=\(sign)"
        case .sendCode(let phone, let type):
            var url = urlPath + "&phone=\(phone)"
            if type.count > 0 {
                url = urlPath + "&phone=\(phone)&type=\(type)"
            }
            return url
        case .sendEmailCode(let email): return urlHalfPath + "&email=\(email)"
        case .phoneNumLogin(let phone, let sessionid, let code, let passwd, let invite):
            if passwd.count == 0 {
                return urlPath + "&phone=\(phone)&sessionid=\(sessionid)&code=\(code)"
            }else if invite.count == 0 {
                return urlPath + "&phone=\(phone)&sessionid=\(sessionid)&passwd=\(passwd)&code=\(code)"
            }
            return urlPath + "&phone=\(phone)&sessionid=\(sessionid)&code=\(code)&passwd=\(passwd)&invite=\(invite)"
        case .register(let user_name, let passwd, let t, let sign, let invite):
            if invite.count == 0 {
                return urlPath + "&passwd=\(passwd)&user_name=\(user_name)&t=\(t)&sign=\(sign)"
            }
            return urlPath + "&passwd=\(passwd)&user_name=\(user_name)&t=\(t)&sign=\(sign)&invite=\(invite)"
        case .home(let type, let gameType, let page):
            var uid = ""
            if let user_id = UserDefaultsManager.getString(forKey: .uid) {
                uid = user_id
            }
            let tStr = RaeRequestParameterConfig.shared.getTStr()
            let sign = RaeRequestParameterConfig.shared.encrySign()
            return urlPath + "&type=\(type)&games_type=\(gameType)&p=\(page)&uid=\(uid)&t=\(tStr)&sign=\(sign)"
        case .homeRecommend(let page): return V5UrlPath + "&p=\(page)"
        case .homeWuKong(let gid, let page): return V5UrlPath + "&gid=\(gid)&p=\(page)"
        case .dynamicTopic(let keyword): return V5UrlPath + "&keyword=\(keyword)"
        case .dynamicGame(let keyword): return V5UrlPath + "&keyword=\(keyword)"
        case .infolist(let class_id, let page, let keyword): return V5UrlPath + "&class_id=\(class_id)&p=\(page)&keyword\(keyword)"
        case .gameList(let gameType, let page): return urlPath + "&fenlei_id=\(gameType)&type=\(gameType)&p=\(page)"
        case .commitList(let gameId, let page, let sortby): return urlHalfPath + "&id=\(gameId)&p=\(page)&sortby=\(sortby)"
        case .dynamicList(let page):
            if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
                return urlPath + "&p=\(page)&uid=\(uid)"
            }
            return urlPath + "&p=\(page)"
        case .dynamicLike(let type, let dynamicID): return urlPath + "&type=\(type)&id=\(dynamicID)"
        case .dynamicDetail(let is_look, let dynamicID):
            if is_look.count > 0 {
                return urlPath + "&is_look=\(is_look)&id=\(dynamicID)"
            }
            return urlPath + "&id=\(dynamicID)"
        case .dynamicCommitList(let dynamicID, let page): return V5UrlPath + "&id=\(dynamicID)&p=\(page)"
//        case .dynamicCommit(let dynamicID, let pid, let content): return urlPath + "&dongtai_id=\(dynamicID)&pid=\(pid)&content=\(content)"
        case .messageList(let page): return urlPath + "&p=\(page)"
        case .readAllList(let id): return urlPath + "&id=\(id)"
        case .delMessge(let id): return urlPath + "&id=\(id)"
        case .gameTagList(let gameID): return V5UrlPath + "&gid=\(gameID)"
        case .gameDetailTop(let gameID): return urlHalfPath + "&id=\(gameID)"
        case .gameDetailInfo(let gameID): return urlHalfPath + "&id=\(gameID)"
        case .getSonCommitList(let pid): return urlHalfPath + "&pid=\(pid)"
        case .mineInfo(let uid): 
            if let user_id = UserDefaultsManager.getString(forKey: .uid), user_id == uid {
                return urlPath + "&uid=\(uid)"
            }else{
                let tStr = RaeRequestParameterConfig.shared.getTStr()
                let sign = uid + tStr + "fsd213ewdsadqwe2121213edsad"
                let signMD5 = RaeRequestParameterConfig.shared.md5HexDigest(sign)
                return urlPath + "&uid=\(uid)&t=\(tStr)&sign=\(signMD5)"
            }
        case .communityTop(let communityID): return V5UrlPath + "&id=\(communityID)"
        case .communityList(let page, let type, let keyword, let uid, let is_bbs): return V5UrlPath + "&p=\(page)&type=\(type)&keyword=\(keyword)&uid=\(uid)&is_bbs=\(is_bbs)"
        case .followCommunityList(let uid): return V5UrlPath + "&uid=\(uid)"
        case .communityFollow(let communityID): return V5UrlPath + "&id=\(communityID)"
        case .communityPostList(let communityID, let type,let sortby, let page, let keyword): return V5UrlPath + "&id=\(communityID)&type=\(type)&sortby=\(sortby)&p=\(page)&keyword=\(keyword)"
        case .strategyInfo(let communityID, let page): return V5UrlPath + "&id=\(communityID)&p=\(page)"
        case .strategyPostInfo(let newId): return V5UrlPath + "&id=\(newId)"
        case .strategyPostCommitList(let newId, let uid, let sortby): return V5UrlPath + "&id=\(newId)&uid=\(uid)&sortby=\(sortby)"
        case .likeStrategyPost(let pid, let puid, let type):
            var uid = ""
            if let user_id = UserDefaultsManager.getString(forKey: .uid) {
                uid = user_id
            }
            let tStr = RaeRequestParameterConfig.shared.getTStr()
            let sign = RaeRequestParameterConfig.shared.encrySign()
            return V5UrlPath + "&pid=\(pid)&puid=\(puid)&type=\(type)&uid=\(uid)&t=\(tStr)&sign=\(sign)"
        case .mallList(let page): return urlPath + "&p=\(page)"
        case .mallDetail(let goodsID): return urlHalfPath + "&id=\(goodsID)"
        case .collectGoods(let goodsID, let type): return urlHalfPath + "&id=\(goodsID)&type=\(type)"
        case .cancelCollectGoods(let goodsID, let type):
            var uid = ""
            if let user_id = UserDefaultsManager.getString(forKey: .uid) {
                uid = user_id
            }
            let tStr = RaeRequestParameterConfig.shared.getTStr()
            let sign = RaeRequestParameterConfig.shared.encrySign()
            return urlHalfPath + "&id=\(goodsID)&type=\(type)&uid=\(uid)&t=\(tStr)&sign=\(sign)"
        case .dailyCheck:
            var uid = ""
            if let user_id = UserDefaultsManager.getString(forKey: .uid) {
                uid = user_id
            }
            let tStr = RaeRequestParameterConfig.shared.getTStr()
            let sign = RaeRequestParameterConfig.shared.encrySign()
            return urlHalfPath + "&uid=\(uid)&t=\(tStr)&sign=\(sign)"
        case .hotSearch: return urlHalfPath
        case .infoCate: return V5UrlPath
        case .searchGames(let keyString, let is_bbs): return urlHalfPath + "&keyword\(keyString)&is_bbs\(is_bbs)"
//        case .addStrategyCommit(let pid, let puid, let type, let content): return V5UrlPath + "&pid=\(pid)&puid=\(puid)&type=\(type)&content=\(content)"
        case .myExchangeList(let page):
            var uid = ""
            if let user_id = UserDefaultsManager.getString(forKey: .uid) {
                uid = user_id
            }
            let tStr = RaeRequestParameterConfig.shared.getTStr()
            let sign = RaeRequestParameterConfig.shared.encrySign()
            return urlPath + "&uid=\(uid)&t=\(tStr)&sign=\(sign)&p=\(page)"
        case .myCollectList(let type, let page): return urlHalfPath + "&type=\(type)&p=\(page)"
        case .delMyCommit(let commitID): return urlPath + "&id=\(commitID)"
        case .getUserInfo:
            var uid = ""
            if let user_id = UserDefaultsManager.getString(forKey: .uid) {
                uid = user_id
            }
            return urlHalfPath + "&uid=\(uid)"
        case .updateUserInfo(let value): return urlHalfPath + "&value=\(value)"
        case .myAddressList: return urlHalfPath
        case .myGiftList(let page): 
            var uid = ""
            if let user_id = UserDefaultsManager.getString(forKey: .uid) {
                uid = user_id
            }
            let tStr = RaeRequestParameterConfig.shared.getTStr()
            let sign = RaeRequestParameterConfig.shared.encrySign()
            return urlPath + "&uid=\(uid)&t=\(tStr)&sign=\(sign)&p=\(page)"
        case .likeInfo(let infoID): 
            var uid = ""
            if let user_id = UserDefaultsManager.getString(forKey: .uid) {
                uid = user_id
            }
            let tStr = RaeRequestParameterConfig.shared.getTStr()
            let sign = RaeRequestParameterConfig.shared.encrySign()
            return V5UrlPath + "&id=\(infoID)&uid=\(uid)&t=\(tStr)&sign=\(sign)"
        case .likeGameCommit(let commitID): return urlHalfPath + "&id=\(commitID)"
        case .getLaunchScreen: return urlHalfPath
        case .delDynamic(let dynamicID): return urlPath + "&id=\(dynamicID)"
        case .addAppointment(let gameID):
            var uid = ""
            if let user_id = UserDefaultsManager.getString(forKey: .uid) {
                uid = user_id
            }
            let tStr = RaeRequestParameterConfig.shared.getTStr()
            let sign = RaeRequestParameterConfig.shared.encrySign()
            return urlPath + "&gid=\(gameID)&uid=\(uid)&t=\(tStr)&sign=\(sign)"
        case .otherDynamicList(let uid, let page):            
            return urlPath + "&user_id=\(uid)&p=\(page)"
        case .addBlackList(let uid):
            return urlPath + "&black_id=\(uid)"
        case .delBlackList(let uid):
            return urlPath + "&black_id=\(uid)"
        case .blackList(let page):
            return urlPath + "&p=\(page)"
        case .activeList(let gid):
            return urlPath + "&gid=\(gid)"
        case .appUpdate(let codeVersion):
            return urlHalfPath + "&versionCode=\(codeVersion)&ios=1"
        case .delCommit(let commitID):
            return urlHalfPath + "&id=\(commitID)"
        case .delPost(let postID):
            return V5UrlPath + "&id=\(postID)"
        case .delDynamicCommit(let commitID):
            return V5UrlPath + "&id=\(commitID)"
        case .delForumCommit(let commitID):
            return V5UrlPath + "&id=\(commitID)"
        case .squareTopicList(let page, let topicID):
            return V5UrlPath + "&p=\(page)&subject_id=\(topicID)"
        case .squareMemberList(let gid, let role, let keyword, let page):
            return V5UrlPath + "&gid=\(gid)&role=\(role)&keyword=\(keyword)&p=\(page)"
        case .squareBanMember(let gid, let page):
            return V5UrlPath + "&gid=\(gid)&p=\(page)"
        case .forumMemberBan(let gid, let user_id):
            return V5UrlPath + "&gid=\(gid)&user_id=\(user_id)"
        case .forumMemberCancelBan(let gid, let user_id):
            return V5UrlPath + "&gid=\(gid)&user_id=\(user_id)"
        case .forumAddAdmin(let gid, let user_id):
            return V5UrlPath + "&gid=\(gid)&user_id=\(user_id)"
        case .forumCancelAdmin(let gid, let user_id):
            return V5UrlPath + "&gid=\(gid)&user_id=\(user_id)"
        case .adminPerm(let gid, let user_id):
            return V5UrlPath + "&gid=\(gid)&user_id=\(user_id)"
        case .postUpOrDown(let id):
            return V5UrlPath + "&id=\(id)"
        case .postTopOrDown(let id):
            return V5UrlPath + "&id=\(id)"
        case .myForumList(let page):
            return V5UrlPath + "&p=\(page)"
        case .otherForumList(let uid, let page):
            return V5UrlPath + "&user_id=\(uid)&p=\(page)"
//        case .delAddress(let addressID, let uid):
//            let tStr = RaeRequestParameterConfig.shared.getTStr()
//            let sign = RaeRequestParameterConfig.shared.encrySign()
//            return urlHalfPath + "&id=\(addressID)&uid=\(uid)&t=\(tStr)&sign=\(sign)"
            
        default:
            return ""
        }
    }
    
    /**
     var uid = ""
     if let user_id = UserDefaultsManager.getString(forKey: .uid) {
         uid = user_id
     }
     let tStr = RaeRequestParameterConfig.shared.getTStr()
     let sign = RaeRequestParameterConfig.shared.encrySign()
     */
    
    /// 请求
    var request: URLRequest {
        if isGetRequest {
            return getRequest
        }else {
            return postRequest
        }
    }
    
    /// Get请求
    /// Get Request
    private var getRequest: URLRequest {
        var request = URLRequest.init(url: URL.init(string: getRequestUrl) ?? URL.init(string: urlPath)!, timeoutInterval: 30)
        request.httpMethod = HTTPMethod.get.rawValue
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.setValue(ASIdentifierManager.shared().advertisingIdentifier.uuidString, forHTTPHeaderField: "imei")
        if let uid = UserDefaultsManager.getString(forKey: .uid) {
            request.setValue(uid, forHTTPHeaderField: "uid")
        }
        request.setValue(RaeRequestParameterConfig.shared.getTStr(), forHTTPHeaderField: "t")
        request.setValue(RaeRequestParameterConfig.shared.encrySign(), forHTTPHeaderField: "sign")
        request.setValue("1", forHTTPHeaderField: "ios")
        return request
    }
    
    /// Post请求
    /// Post Request
    private var postRequest: URLRequest {
        var urlStr = urlPath
        if !isFullUrlRequest {
            urlStr = urlHalfPath
        }
        var request = URLRequest.init(url: URL.init(string: urlStr)!, timeoutInterval: 30)
        request.httpMethod = HTTPMethod.post.rawValue
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        if isUploadImage {
            request.setValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
            request.setValue(RaeRequestParameterConfig.shared.host, forHTTPHeaderField: "Host")
            request.setValue("chunked", forHTTPHeaderField: "Transfer-Encoding")
        }
        if let uid = UserDefaultsManager.getString(forKey: .uid) {
            request.setValue(uid, forHTTPHeaderField: "uid")
        }
        request.setValue(RaeRequestParameterConfig.shared.getTStr(), forHTTPHeaderField: "t")
        request.setValue(RaeRequestParameterConfig.shared.encrySign(), forHTTPHeaderField: "sign")
        request.setValue("1", forHTTPHeaderField: "ios")
        let data = try? JSONSerialization.data(withJSONObject: parameters, options: JSONSerialization.WritingOptions.prettyPrinted)
        request.httpBody = data
        return request
    }
    
}
